/*
 * Copyright (c) 2009, David A. Freels Sr.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification, are permitted provided that
 * the following conditions are met:
 *
 *     * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
 *     * Neither the name of the <ORGANIZATION> nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
 * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

package net.whippetcode.plugins.intellij.hudson.parser;

import net.whippetcode.plugins.intellij.hudson.domain.test.TestClass;
import net.whippetcode.plugins.intellij.hudson.domain.test.TestMethod;
import net.whippetcode.plugins.intellij.hudson.domain.test.TestPackage;
import net.whippetcode.plugins.intellij.hudson.domain.test.TestStatus;
import net.whippetcode.plugins.intellij.hudson.util.XMLUtil;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPathExpressionException;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * This class handles parsing of test reports.
 *
 * @author David A. Freels Sr.
 */
public class TestHandler
{
	private static final String TEST_RESULT = "testResult";
	private static final String SUREFIRE_AGGREGATED_REPORT = "surefireAggregatedReport";
	private static final String NAME = "name";
	private static final String STATUS = "status";
	private static final String STATU = "statu";
	private static final String STDOUT = "stdout";
	private static final String STDERR = "stderr";
	private static final String ERROR_STACK_TRACE = "errorStackTrace";
	private static final String SUREFIRE_CHILD_REPORT = "childReport";
	private static final String SUREFIRE_RESULT = "result";
	private static final String TEST_CASE = "suite/case";
	private static final String CLASSNAME = "className";

	private List<TestPackage> tests = new ArrayList<TestPackage>();

	public TestHandler(URL url) throws IOException, ParserConfigurationException, SAXException, XPathExpressionException
	{
		Document doc = XMLUtil.createDocument(url);
		Element element = doc.getDocumentElement();

		if (TEST_RESULT.equals(element.getTagName()))
		{
			//Parse the packages
			parsePackages(element);
		}
		else if (SUREFIRE_AGGREGATED_REPORT.equals(element.getTagName()))
		{
			NodeList packages = XMLUtil.getElements(SUREFIRE_CHILD_REPORT, element);

			Node report;
			for (int i = 0; i < packages.getLength(); i++)
			{
				report = packages.item(i);
				parsePackages(XMLUtil.getElement(SUREFIRE_RESULT, report));
			}
		}
	}

	private void parsePackages(Node element)
		 throws XPathExpressionException
	{
		NodeList packages = XMLUtil.getElements(TEST_CASE, element);
		int childCount = packages.getLength();
		Node pkgNode;

		TestPackage pkg = null;
		TestClass clz = null;
		String className;
		String packageName;
		String name;
		String methodName;
		Map<String, TestPackage> packageMap = new HashMap<String, TestPackage>();
		Map<String, TestClass> classMap = new HashMap<String, TestClass>();
		for (int i = 0; i < childCount; i++)
		{
			pkgNode = packages.item(i);
			className = XMLUtil.getTextElement(CLASSNAME, pkgNode);
			packageName = className.substring(0, className.lastIndexOf("."));
			name = className.substring(className.lastIndexOf(".") + 1);
			methodName = XMLUtil.getTextElement(NAME, pkgNode);

			//Make sure we have the current package
			if (!packageMap.containsKey(packageName))
			{
				if (pkg != null && clz != null)
				{
					pkg.addTestClass(clz);
				}
				
				pkg = new TestPackage();
				pkg.setName(packageName);
				tests.add(pkg);
				packageMap.put(packageName, pkg);
			}
			else
			{
				pkg = packageMap.get(packageName);
			}

			if (!classMap.containsKey(className))
			{
				clz = new TestClass();
				clz.setName(name);
				pkg.addTestClass(clz);
				classMap.put(className, clz);
			}
			else
			{
				clz = classMap.get(className);
			}

			//Capture the class stdout and stderr since there will be no methods
			if (methodName.equals(className))
			{
				if (XMLUtil.hasContent(ERROR_STACK_TRACE, pkgNode))
				{
					clz.setStandardError(XMLUtil.getTextElement(ERROR_STACK_TRACE, pkgNode));
				}
				else if (XMLUtil.hasContent(STDERR, pkgNode))
				{
					clz.setStandardError(XMLUtil.getTextElement(STDERR, pkgNode));
				}
				if (XMLUtil.hasContent(STDOUT, pkgNode))
				{
					clz.setStandardOutput(XMLUtil.getTextElement(STDOUT, pkgNode));
				}
			}
			//Continue adding methods
			else
			{
				TestMethod method = new TestMethod();
				method.setName(XMLUtil.getTextElement(NAME, pkgNode));

				if (XMLUtil.hasContent(STATU, pkgNode))
				{
					getStatus(STATU, pkgNode, method);
				}
				else if (XMLUtil.hasContent(STATUS, pkgNode))
				{
					getStatus(STATUS, pkgNode, method);
				}

				if (XMLUtil.hasContent(ERROR_STACK_TRACE, pkgNode))
				{
					method.setStandardError(XMLUtil.getTextElement(ERROR_STACK_TRACE, pkgNode));
				}
				else if (XMLUtil.hasContent(STDERR, pkgNode))
				{
					method.setStandardError(XMLUtil.getTextElement(STDERR, pkgNode));
				}
				if (XMLUtil.hasContent(STDOUT, pkgNode))
				{
					method.setStandardOutput(XMLUtil.getTextElement(STDOUT, pkgNode));
				}
				clz.addTestMethod(method);
			}
		}

		//Ensure that each package has the proper status
		for (TestPackage testPackage : packageMap.values())
		{
			testPackage.calculatePackageStatus();
		}
	}

	private void getStatus(String expression, Node mtdNode, TestMethod method)
		 throws XPathExpressionException
	{
		String status;
		status = XMLUtil.getTextElement(expression, mtdNode);
		if (status != null && status.trim().length() > 0)
		{
			method.setStatus(TestStatus.valueOf(status));
		}
	}

	public List<TestPackage> getPackages()
	{
		return tests;
	}
}
